/*
 * Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.base.ctrl;

import com.opensso.sdk.client.SessionEnum;
import com.pitop.base.LoginConfig;
import com.pitop.core.entity.BeanRet;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.tools.redis.RedisUtils;
import com.pitop.core.tools.security.Md5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * support登录控制器
 * Created by jiyan on 2017/8/17.
 */
@Controller
@RequestMapping("/login/")
@EnableConfigurationProperties(LoginConfig.class)
@Api(value = "管理员登录接口", description = "管理员登录")
public class LoginCtrl {

    private final static Logger logger = LoggerFactory.getLogger(LoginCtrl.class);

    @Autowired
    private  LoginConfig loginConfig;

    @Resource
    private RedisUtils redisUtils;

    /**
     * 管理员登录：目前登录数据是从login.config配置文件中读取的
     *
     * @param account  登录账户
     * @param pwd      密码
     * @param response
     * @return
     */
    @ApiOperation(value = "管理员登录")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "登录账户", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pwd", value = "密码", paramType = "query", dataType = "String")
    })
    @ResponseBody
    public BeanRet login(String account, String pwd, HttpServletResponse response) throws IOException {
        try {
            //参数非空验证
            Assert.hasText(account, BaseException.BaseExceptionEnum.Empty_Param.toString());
            Assert.hasText(pwd, BaseException.BaseExceptionEnum.Empty_Param.toString());

            //从配置文件中获取账户和密码
            String username = loginConfig.getUsername();
            String password = loginConfig.getPassword();
            //判断输入的账户和密码，与系统内的账户和密码是否一致
            if (account.equals(username) && pwd.equals(password)) {
                String md5 = Md5.md5(username);
                String token = "Support:" + md5;
                redisUtils.set(token, username, 30*60);
                response.addHeader(SessionEnum.Token.name(), token);
                return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, username);
            } else {
                return BeanRet.create();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return BeanRet.create("账户或密码错误");
        }
    }

    /**
     * 注销登录
     *
     * @param response response对象
     * @return BeanRet
     */
    @ApiOperation(value = "注销登录")
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    @ResponseBody
    public BeanRet logout(HttpServletResponse response, HttpServletRequest request) {
        String token = request.getHeader(SessionEnum.Authorization.name());
        redisUtils.del(token);
        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success);
    }
}
